/*
localStorage.userInfo = {
    userName:
    id:
    selectedLevel:
    score: 0 
    time: 0 
    scoreMax:
    timeMin:
};
*/

/*
comments body:
{user: ,id:}
 */

/*
user comments body:
{user:, score:, time:}
 */
var userInfo = {};

var gamePlatUrl = "https://api.github.com/gists/d0d98ee87c48ce742b41775b1b9f7a2c/comments";

var token = "token f64c32f8a963fbc941722743ad0ef3c194c10eae";

function getUserInfo() {
    console.log("getUserInfo");

    //check localStorage.
    if(localStorage.userInfo) {
        userInfo = JSON.parse(localStorage.userInfo);
        var userName = userInfo.userName;

        var url = gamePlatUrl;
        $.get(url, function(data, status){
            
            var len = data.length;
            for(var i = 0; i < len; i++) {
                var user = JSON.parse(data[i].body).user;
                if(user === userName) {
                    getUserScore();

                    break;
                }
            }
        });

        
    }
}

function getUserScore() {
    console.log("getUserScore");

    userInfo = JSON.parse(localStorage.userInfo);
    var id = userInfo.id;

    var url = "https://api.github.com/gists/" + id + "/comments";

    $.get(url, function(data, status) {
        var len = data.length;
        
        var item = data[len - 1].body;

        var scoreMax = JSON.parse(item).score;
        var timeMin = JSON.parse(item).time;

        userInfo.scoreMax = scoreMax;
        userInfo.timeMin = timeMin;

        localStorage.userInfo = JSON.stringify(userInfo);
        renderUserInfo();
    });
}

function renderUserInfo() {
    console.log("renderUserInfo");

    userInfo = JSON.parse(localStorage.userInfo);
    console.log(userInfo);
    
    $("#my-time").html((Number(userInfo.timeMin)/60).toFixed(2));
    $("#my-score").html(userInfo.scoreMax);

    $("#score-now").html(userInfo.score);
    $("#time-now-min").html((Number(userInfo.time)/60).toFixed(0));
    $("#time-now-s").html((Number(userInfo.time))%60);

    $("#username").html(userInfo.userName);
}

$("#login").on("click", function() {
    var name = prompt("请输入用户名：");

    if(name) {
        
        var url = gamePlatUrl;

        $.get(url, function(data,status){
            var len = data.length;
            for(var i = 0; i < len; i++) {
                var item = JSON.parse(data[i].body);
                var user = item.user;
                if(user === name) {
                    userInfo.userName = name;
                    userInfo.id = item.id;

                    userInfo.score = 0;
                    userInfo.time = 0;

                    userInfo.selectedLevel = "Level 1";

                    localStorage.userInfo = JSON.stringify(userInfo);

                    getUserInfo();

                    $("#username").removeClass("hidden");
                    $("#login").removeClass("hidden").addClass("hidden");
                    $("#logout").removeClass("hidden");

                    break;
                }
            }

            if(i == len) {
                createUser(name);
                $("#username").removeClass("hidden");
                $("#login").removeClass("hidden").addClass("hidden");
                $("#logout").removeClass("hidden");
            }
        });
        userInfo.login = true;
    }
});

function createUser(name) {

    console.log("createUser");
    //create a gist for user
    var filename = name + ".txt"
    var gistBody = {
      description: "game data for user",
      public: false,
      files: {}
    };

    gistBody.files[filename] = {
        content: "game data for user"
    };
    
    $.ajax({
        type: "post",
        url: "https://api.github.com/gists",
        headers: {
            Authorization: token,
        },
        dataType: "json",
        data: JSON.stringify(gistBody),
    }).done(function(data) {
        var id = data.id;

        userInfo = {};
        userInfo.userName = name;
        userInfo.id = id;

        userInfo.score = 0;
        userInfo.time = 0;

        userInfo.scoreMax = 0;
        userInfo.timeMin = 0;

        userInfo.selectedLevel = "Level 1";

        localStorage.userInfo = JSON.stringify(userInfo);
        renderUserInfo();

        var userUrl = "https://api.github.com/gists/" + id + "/comments";

        var body = {
            "body": '{"score":"0","time":"0"}'
        };

        var platStr = '{"user":' + '"' + name + '"' + ',' + '"id":' + '"' + id + '"}'; 
        var platBody = {
            "body": platStr
        };

        $.ajax({
            type: "post",
            url: gamePlatUrl,
            headers: {
                Authorization: token,
            },
            dataType: "json",
            data: JSON.stringify(platBody),
        });

        $.ajax({
            type: "post",
            url: userUrl,
            headers: {
                Authorization: token,
            },
            dataType: "json",
            data: JSON.stringify(body),
        });
    });   
}